package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 微信服务实现类
 * @author elina
 */
@Service
@Slf4j
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    // @Value("${wechat.appId}")
    // TODO Bug 属性注入错误，直接赋值
    private final String appid = "wxd9d8fbd3460018fb";

    @Value("${wechat.appSecret}")
    private String secret;

    /**
     * 获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        Map<String,Object> params = Map.of("appid",appid,"secret",secret,"js_code",code);
        String json = HttpUtil.get(REQUEST_URL, params);
        if (json != null) {
            JSONObject result = JSONUtil.parseObj(json);
            if (ObjectUtil.isNotEmpty(result.getInt("errcode"))) {
                throw new BaseException("获取OpenId失败！");
            }
            return result.getStr("openid");
        }
        throw new BaseException("获取OpenId失败！");
    }

    /**
     * 获取手机号
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {
        String token = getToken();
        Map<String, Object> param = Map.of("code",phoneCode);
        String json = HttpUtil.post(PHONE_REQUEST_URL + token, JSONUtil.toJsonStr(param));
        if (StringUtils.isEmpty(json)) {
            throw new BaseException("获取手机号失败！");
        }
        // 判断接口响应是否出错
        JSONObject result = JSONUtil.parseObj(json);
        if (result.getInt("errcode" ) != 0 )
            throw new BaseException("获取手机号失败！");
        return result.getJSONObject("phone_info").getStr("phoneNumber");
    }

    /**
     * 获取token
     * @return
     */
    private String getToken() {
        Map<String,Object> params = Map.of("appid",appid,"secret",secret);
        String json = HttpUtil.get(TOKEN_URL, params);
        if (StringUtils.isEmpty(json)) {
            throw new BaseException("获取Token失败！");
        }
        JSONObject result = JSONUtil.parseObj(json);
        if (ObjectUtil.isNotEmpty(result.getInt("errcode"))) {
            log.error(result.getStr("errmsg"));
            throw new BaseException("获取Token失败！");
        }
        return result.getStr("access_token");
    }
}
